package com.freecloud.tomcat.bio;

import com.freecloud.tomcat.bio.http.FreeRequest;
import com.freecloud.tomcat.bio.http.FreeResponse;
import com.freecloud.tomcat.bio.http.FreeServlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * tomcat启动类
 *
 * @Author: maomao
 * @Date: 2021/8/30 10:02 上午
 */
public class BIOTomcatMain {

    private int port = 8088;
    private ServerSocket serverSocket;
    private Properties webxml = new Properties();
    private Map<String, FreeServlet> servletMap = new HashMap<>();

    public static void main(String[] args) {
        new BIOTomcatMain().start();
    }

    public void start() {
        //解析配置文件
        init();
        //启动服务
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("Free Tomat 已启动，监听端口：" + this.port);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                //获得请求信息，解析Http协议内容
                process(clientSocket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void process(Socket clientSocket) throws IOException {
        try (InputStream is = clientSocket.getInputStream(); OutputStream os = clientSocket.getOutputStream();) {
            FreeRequest request = new FreeRequest(is);
            FreeResponse response = new FreeResponse(os);

            String url = request.getUrl();
            if (servletMap.containsKey(url)) {
                servletMap.get(url).service(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            clientSocket.close();
        }
    }

    private void init() {
        String web_info = this.getClass().getResource("/").getPath();
        try {
            FileInputStream fin = new FileInputStream(web_info + "web.properties");
            webxml.load(fin);
            for (Object k : webxml.keySet()) {
                String key = k.toString();
                if (key.endsWith("url")) {
                    String servletName = key.replaceAll("\\.url$", "");
                    String url = webxml.getProperty(key);
                    String className = webxml.getProperty(servletName + ".className");
                    FreeServlet freeServlet = (FreeServlet)Class.forName(className).newInstance();
                    //url与servlet绑定
                    servletMap.put(url, freeServlet);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
